﻿using Hangfire;
using ServiceMs.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;

namespace ServiceMs.Base
{
    public static class ServiceHandle
    {
        //要执行的任务列表
        static string configFileName = AppDomain.CurrentDomain.BaseDirectory + "Config\\" + "BTWindowsServerConfig.xml";

        public static void InitServices()
        {
            try
            {

                LogHelper.WriteLog("开始读取配置文件");

                //要执行的任务列表
                List<ServerInfo> _serverList = null;
                //如果配置文件不存在则创建，否则任务列表从配置文件中读取
                if (!File.Exists(configFileName))
                {
                    XmlHelper.WriteServerInfoToXml(ServerInfos.ServerInfoList);
                }
                else
                {
                    _serverList = XmlHelper.ReadServerInfosXmlToDtos();
                }
                if (_serverList == null)
                {
                    _serverList = ServerInfos.ServerInfoList;
                }
                LogHelper.WriteLog("配置文件读取完成");

                LogHelper.WriteLog("开始添加任务列表");
              
                var serverInfos = _serverList.Where(t => t.IsUsable == true).ToList();
                foreach (var serverInfo in serverInfos)
                {
                    AddJob(serverInfo);
                }
                LogHelper.WriteLog("任务列表添加完成");

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("服务启动异常：" + ex.Message);
            }
        }

        /// <summary>
        /// 添加任务到调度
        /// </summary>
        /// <param name="methodServerInfo"></param>
        public static void AddJob(ServerInfo methodServerInfo)
        {
            try
            {
                var type = typeof(ServerMethod);
                MethodInfo method = type.GetMethod(methodServerInfo.TaskMethod);

                if (method != null)
                {
                    RecurringJob.AddOrUpdate(methodServerInfo.TaskName + string.Format("({0})", methodServerInfo.Id),
                        () => ServerMethod.Execute(methodServerInfo.TaskMethod, methodServerInfo),
                        methodServerInfo.ExecTime, TimeZoneInfo.Local);
                }
                else if (methodServerInfo.TaskMethod.ToLower().StartsWith("http://")
                         || methodServerInfo.TaskMethod.ToLower().StartsWith("https://"))
                {
                    RecurringJob.AddOrUpdate(methodServerInfo.TaskName + string.Format("({0})", methodServerInfo.Id),
                        () => ServerMethod.ExcuteApi(methodServerInfo),
                        methodServerInfo.ExecTime, TimeZoneInfo.Local);
                }
                else
                {
                    LogHelper.WriteLog("加入任务队列失败，未查找到任务执行方法", methodServerInfo.TaskName);
                    return;
                }
                LogHelper.WriteLog("加入任务队列成功", methodServerInfo.TaskName);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("加入任务队列失败," + ex.Message, methodServerInfo.TaskName);
            }
        }

        public static void ClearJob()
        {
            if (!File.Exists(configFileName))
            {
                return;
            }
            var _serverList = XmlHelper.ReadServerInfosXmlToDtos();
            foreach (ServerInfo serverInfo in _serverList)
            {
                RecurringJob.RemoveIfExists(serverInfo.TaskName + string.Format("({0})", serverInfo.Id));
            }
        }

        public static void DeleteJob(ServerInfo serverInfo) 
        {
            RecurringJob.RemoveIfExists(serverInfo.TaskName + string.Format("({0})", serverInfo.Id));
        }
    }
}